<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\CommissionLog;
use app\common\model\HandCard as HandCardM;
use app\common\model\Factor;
use app\common\model\Fenorder;
use app\common\model\Order;
use app\common\model\Project;
use Exception;
use think\Db;
/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Index extends Auth
{
    public $noNeedLogin = ['index,avatar_base64'];

    public function index(){
        $noticeData = Db::name('qt_notic')->where(['status'=>1])->field('id,title')->limit(10)->order('id desc')->select();
        $data['noticeData'] = $noticeData;
        //banner
        $banner = Db::view('qt_banner_position', 'id,name,is_flash,url')
            ->view('qt_banner', 'imgurl,create_time,active_id', 'qt_banner.position_id=qt_banner_position.id', 'left')
            ->where(['qt_banner_position.name_key'=>'index_banner','qt_banner.status'=>'0'])
            ->order('qt_banner.id','desc')
            ->select();
        foreach ($banner as $key =>$value){
            $imgUrl = get_img_path($value['imgurl']);
            $banner[$key]['imgurl'] = $imgUrl;
        }
        $data['banner']  = $banner;
        $this->result('查询成功',$data,200);
    }




    /**
     * base64图片上传
     */
    public function avatar_base64() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['imgurl'])){
                $this->result('请上传图片','',204);
            }
            $bg = $data['imgurl'];//获取图片流
            //$str =base64_encode(base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $bg)));
            //if($str!=$bg){
            //    $this->result('请上传正确的图片','',204);
            //}
            $image_content=base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $bg));
            $filename=time().rand('1111','9999').'.jpg';
            $path='uploads/avatar/'.date('Ymd');
            $dir=$path.'/'.$filename;
            if(!is_dir($path)){
                mkdir($path);
            }
            file_put_contents($dir, $image_content);
            $imgurl='uploads/avatar/'.date('Ymd').'/'.$filename;
            $data1 = array(
                'path' => $imgurl,
                'name' => $filename,
                'module' => 'index',
                'md5' => md5($filename),
                'thumb' => $imgurl,
                'url' => '1',
                'siza' => '0',
                'mime' => $filename,
                'ext' => '0',
                'sha1' => sha1($filename),
                'create_time' => time(),
                'update_time' => time(),
            );
            $re = Db::name('admin_attachment')->insertGetId($data1);
            $attac=get_img_path($re);
            $data=array(
                'imgurl'=>$attac,
                'img_id'=>$re,
            );
            $this->result('上传成功',$data,200);
        }else{
            $this->result('error','',204);
        }
    }


    /**
     * 更换技师
     */
    public  function  change_engineer(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $find = Db::name('qt_order_queue')
                ->where(['user_id'=>$getData['engineer_id']])
                ->find();
            //项目子订单
            $orderProject = Db::name('qt_order_project')->where('id',$find['order_project_id'])->find();
            //退技师限制
            if($orderProject['start_time'] != null){
                $time = ( time() - $orderProject['start_time'] ) / 60;
                $time = ceil($time);
                if($this->storeInfo['change_engineer_block'] != '0'){
                    if($time > $this->storeInfo['change_engineer_block']){
                        $this->result('上钟超过设置时间，无法更换技师', '', 204);
                    }
                }
            }
            if($orderProject['start_time'] == null){
                $startTime = time();
            }else{
                $startTime = $orderProject['start_time'];
            }
            //有段位的删除段位费
            $duanweiData = Db::name('qt_duanwei')
                ->where("FIND_IN_SET(" . $getData['engineer_id'] . ",engineer_id)")
                ->where(['project_id'=>$orderProject['project_id']])
                ->find();
            if(!empty($duanweiData)){
                //查找技师是否下了商品订单
                $orderGoodsItem = Db::name('qt_product_order_item')
                    ->where(['goods_id'=>$duanweiData['product_id'],'room_id'=>$orderProject['room_id'],'sale_id'=>$getData['engineer_id'],'business_type'=>'5'])
                    ->find();
                if(!empty($orderGoodsItem)){
                    \app\common\model\Duanwei::delDuanweiPrice($orderGoodsItem['id']);
                }
            }
            //删除提成记录
            Db::name('qt_commission_log')->where(['order_project_id'=>$orderProject['id'],'type'=>'1'])->delete();
            //给手牌减金额
            HandCardM::decHandCardMoney($orderProject['id'],$orderProject['hand_card_id'],'1');
            if($getData['type'] == '1'){
                //新订单信息
                $newOrderProjectInsert = [
                    'store_id'=>$orderProject['store_id'],
                    'name'=>$orderProject['name'],
                    'created_order_id'=>$orderProject['created_order_id'],
                    'order_id'=>$orderProject['order_id'],
                    'start_time'=>$startTime,
                    'project_id'=>$orderProject['project_id'],
                    'room_id'=>$orderProject['room_id'],
                    'hand_card_id'=>$orderProject['hand_card_id'],
                    'order_type'=>'1',
                    'num'=>$orderProject['num'],
                    'price'=>$orderProject['price'],
                    'status'=>'1',
                    'is_add'=>'1',
                    'is_change'=>'1',
                    'created_time'=>time()
                ];
                //安排技师
                $orderProjectId = Db::name('qt_order_project')->insertGetId($newOrderProjectInsert);
                $project = Db::name('qt_order_project')->where('id',$orderProjectId)->find();
                $orderModel = new Order();
                $orderModel->scheduling($project,$getData['sex'],$this->storeInfo);
                //更新老项目数据
                Db::name('qt_order_project')->where(['id'=>$orderProject['id']])->update(['status'=>'4','is_change'=>'2']);
                //更新排位
                Db::name('qt_order_queue')->where(['user_id'=>$getData['engineer_id']])
                    ->update([
                        'room_id'=>null,
                        'project_id'=>null,
                        'order_project_id'=>null,
                        'start_time'=>null,
                        'end_time'=>null,
                        'sort'=>$find['old_sort'],
                        'order_user_id'=>0,
                        'return_time'=>time(),
                        'return_room'=>$orderProject['room_id'],
                    ]);
                Db::name('qt_users')->where(['id'=>$getData['engineer_id']])->update(['work_status'=>'1']);
                //修改房间状态
                Db::name('qt_room')->where(['id'=>$orderProject['room_id']])->update(['status_id'=>'2','retreat_time'=>time()]);
                $this->result('操作成功', '', 200);
            }else{
                //点钟
                if(empty($find)){
                    $this->result('项目不存在', '', 204);
                }
                $nowproject=Db::name('qt_order_project')->where('id',$find['order_project_id'])->find();
                if($nowproject['start_time'] != null){
                    if((time()- $nowproject['start_time'] )>= 600){
                        $this->result('超过十分钟无法更换技师', '', 204);
                    }
                }
                $project['order_id'] = $nowproject['order_id'];
                $project['room_id'] = $orderProject['room_id'];
                $project['hand_card_id'] = $nowproject['hand_card_id'];
                $project['order_type'] = $getData['order_type'];
                $project['status'] = '1';
                $project['project_id'] = $orderProject['project_id'];
                $project['store_id'] = $nowproject['store_id'];
                $project['name'] = $nowproject['name'];
                $project['price'] = $nowproject['price'];
                $project['payment_price'] = $nowproject['price'];
                $project['created_time'] = time();
                $project['is_change']='3';
                Db::name('qt_order_project')->where('id',$find['order_project_id'])->update(['status'=>'4']);
                $neworder_project_id = Db::name('qt_order_project')->insertGetId($project);
                $this->find($nowproject['id'],$orderProject['project_id'],$neworder_project_id,$getData['change_engineer_id']);
                $this->result('更新成功', '', 200);
            }
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 查找合适的技师
     * @param $old_order_project_id[旧订单ID]
     * @param $project_id [项目ID]
     * @param $new_order_project_id [新订单ID]
     * @param $engineer_id [更换技师ID]
     * @return array
     */
    public function find($old_order_project_id,$project_id,$new_order_project_id,$engineer_id){
        //查找当前技师是否在空闲
        $orderQueue = Db::name('qt_users')->where('id',$engineer_id)->find();
        if($orderQueue['work_status'] != '1'){
            $this->result('当前技师不在空闲状态，暂时无法更换','',204);
        }
        $oldorder = Db::name('qt_order_project')->where('id',$old_order_project_id)->find();
        $bigorder = Order::where('id',$oldorder['order_id'])->find();
        //最新排序
        $project= Project::where('id',$project_id)->find();
        //新项目
        $newOrderProject = Db::name('qt_order_project')->where('id',$new_order_project_id)->find();
        if($newOrderProject['order_type']=='3'){
            //call钟
            $rale=$project['call_block_rate'];
        }else if($newOrderProject['order_type']=='2'){
            //点钟
            $rale=$project['dot_block_rate'];
        }
        //老技师数据
        $oldQueue = Db::name('qt_order_queue')->where('user_id',$oldorder['engineer_id'])->find();
        try{
            Db::startTrans();
            //切换旧的技师排序
            Db::name('qt_order_queue')
                ->where('user_id',$oldorder['engineer_id'])
                ->where('order_project_id',$oldorder['id'])
                ->update(
                    [
                        'room_id'=>null,
                        'project_id'=>null,
                        'order_project_id'=>null,
                        'order_user_id'=>null,
                        'status'=>'1',
                        'sort'=>$oldQueue['old_sort'],
                    ]
                );
            //更新技师状态
            Db::name('qt_users')->where('id',$oldorder['engineer_id'])->update(['work_status'=>'1']);
            //更新新技师状态
            Db::name('qt_users')->where('id',$engineer_id)->update(['work_status'=>'5']);
            //删除记录
            Db::name('qt_commission_log')
                ->where(['order_project_id'=>$oldorder['id'],'type'=>'1'])
                ->delete();
            //修改新的技师
            Db::name('qt_order_queue')->where('user_id',$engineer_id)->update(
                [
                    'room_id'=>$oldorder['room_id'],
                    'project_id'=>$project_id,
                    'order_project_id'=>$new_order_project_id,
                    'order_user_id'=>$bigorder['uv_id'],
                    'status'=>'2',
                ]
            );
            //修改房间状态
            Db::name('qt_room')->where(['id'=>$oldorder['room_id']])->update(['status_id'=>'2','retreat_time'=>time()]);
            //新增订单提成明细表
            $commion_log = array(
                'store_id' => $bigorder['store_id'],
                'user_id'=>$engineer_id,
                //'cashier_id'=>$arr['saler_id'],
                'member' => $bigorder['uv_id'],
                'money' => $project['price'],
                'payment_price' => $project['price'],
                'commission' => $project['price'] * $rale / 100,
                'rale' => $rale,
                'product_id' => $project_id,
                'type' => '1',
                'pay_type' => '',
                'created_time' => time(),
                'room_id' => $bigorder['room_id'],
                'is_pay' => '1',
            );
            CommissionLog::create($commion_log);
            //修改分订单的技师id
            Db::name('qt_order_project')->where('id',$new_order_project_id)->update(
                [
                    'engineer_id'=>$engineer_id,
                    'status'=>'1',
                ]
            );
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            $this->result('系统繁忙，请稍后再试','',204);
        }


    }


    /**
     * 获取当前房间等待项目(首页房间等待用)
     */
    public function waitList()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['limit'])) {
                $getData['limit'] = '10';
            }
            $map = [];
            //房间筛选
            if(!empty($getData['room_id'])){
                $map[] = ['w.room_id','=',$getData['room_id']];
            }
            //技师筛选
            if(!empty($getData['work_number'])){
                $userId = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'work_number'=>$getData['work_number']])->value('id');
                if(empty($userId)){
                    $this->result('暂无此技师', [], 200);
                }
                $map[] = ['w.engineer_id','=',$userId];
            }
            //等待时间筛选
            if(!empty($getData['wait_time'])){
                $time = time() - ($getData['wait_time'] * 60);
                $map[] = ['w.create_time','<',$time];
            }
            //项目筛选
            if(!empty($getData['project_id'])){
                $map[] = ['w.project_id','=',$getData['project_id']];
            }
            $data = Db::name('qt_wait')
                ->alias('w')
                ->leftJoin('qt_project p', 'p.id = w.project_id')
                ->leftJoin('qt_room r', 'r.id = w.room_id')
                ->leftJoin('qt_users u', 'u.id = w.engineer_id')
                ->field('w.id,w.project_id,p.name as project_name,r.name as room_name,u.work_number,w.sex,w.create_time,w.create_id,w.engineer_id,w.is_first')
                ->where($map)
                ->where(['w.status'=>'1'])
                ->order('w.id desc')
                ->paginate($getData['limit'])->each(function ($item){
                    $item['create_name'] = Db::name('qt_users')->where('id',$item['create_id'])->value('real_name');
                    $item['end_time'] = Db::name('qt_order_queue')->where('user_id',$item['engineer_id'])->value('end_time');
                    return $item;
                });
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 优先当前技师
     */
    public function waitFirst()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少参数', '', 204);
            }
            $update = Db::name('qt_wait')->where(['id'=>$getData['id']])->update(['is_first'=>$getData['is_first']]);
            if($update !== false){
                $this->result('更新成功', '', 200);
            }
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 删除等位
     */
    public function waitDelete()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少参数', '', 204);
            }
            $wait = Db::name('qt_wait')->where('id',$getData['id'])->find();
            //判断技师数量更改房间状态
            $roomEngineer = Db::name('qt_order_queue')->where(['room_id'=>$wait['room_id']])->count();
            if($roomEngineer <= 1){
                Db::name('qt_room')->where(['id'=>$wait['room_id']])->update(['status_id'=>'10']);
            }
            try{
                Db::startTrans();
                //删除挂账订单
                Db::name('qt_wait')->where(['id'=>$getData['id']])->delete();
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('删除失败','',204);
            }
            $this->result('删除成功','',200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 修改当前技师
     */
    public function waitSave()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少参数', '', 204);
            }
            $wait = Db::name('qt_wait')->where('id',$getData['id'])->update($getData);
            if($wait !== false){
                $this->result('更新成功', '', 200);
            }
        }
        $this->result('无效的请求', '', 204);
    }

}
